package cn.tedu;

import cn.tedu.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Hello world!
 *
 */
public class App {
    
    private static Map<String,HttpServlet> servletMap = new HashMap<>();

    public static void parse(){
        try {
            SAXReader saxReader = new SAXReader();
            Document read = saxReader.read("src/main/resources/web.xml");
            Element rootElement = read.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element e : elements){
                System.out.println(e.elementText("servlet"));
//                System.out.println(e.elementText("mime-type"));
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
    public static void parseServlet(){
        try {
            SAXReader saxReader = new SAXReader();
            Document read = saxReader.read("src/main/resources/servlets.xml");
            Element rootElement = read.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element e : elements){
                String key = e.attributeValue("path");
                String pathServlet = e.attributeValue("className");
                Class<?> aClass = Class.forName(pathServlet);
                Object object = aClass.newInstance();
                servletMap.put(key,(HttpServlet)object);
            }
            System.out.println(read);
            System.out.println(rootElement);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        parseServlet();
//        Set<Map.Entry<String, HttpServlet>> entries = servletMap.entrySet();
//        for (Map.Entry<String,HttpServlet> entry : entries){
//            System.out.println(entry.toString());
//        }

    }
}
